package cn.openea.perpartner.sysuser.service.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.system.entity.dto.UserInfoDto;
import cn.openea.perpartner.system.service.ISysConfigService;
import cn.openea.perpartner.system.service.ISysUserService;
import cn.openea.perpartner.system.enums.AppletsEnums;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-11-25 7:19
 */
@Slf4j
@Component
public class ScheduledService {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private RedisCache redisCache;

    @Scheduled(cron = "0 0 3 * * ?")
    public boolean scheduled() {
        String scheduled = Convert.toStr(redisCache.getCacheObject("sys.scheduled.batch.async"));
        String endTime = DateUtil.now();
        LocalDate startTime;
        if (StrUtil.isBlank(scheduled)) {
            redisCache.setCacheObject("sys.scheduled.batch.async", IdUtil.randomUUID());
            startTime = LocalDate.now().plusDays(-5);
        } else {
            startTime = LocalDate.now().plusDays(-1);
        }
        boolean isOk = false;
        List<String> apps = AppletsEnums.getAppletIds();
        for (String appid : apps) {
            String url = configService.selectConfigByKey(appid + ".account.async.url");
            if (StrUtil.isNotBlank(url)) {
                List<UserInfoDto> userList = userService.selectAsyncList(DateUtil.format(startTime.atStartOfDay(), DatePattern.NORM_DATETIME_PATTERN), endTime, appid);
                Map<String, Object> formMap = new HashMap<>();
                formMap.put("appid", "perpartner");
                formMap.put("wf_num", "R_perpartner_BW008");
                formMap.put("formData", JSON.toJSONString(userList));
                HttpResponse resp = HttpRequest.post(url)
                        .header("sysid", "SysAdmin")
                        .header("syspwd", "pass")
                        .header("userId", "admin")
                        .form(formMap)
                        .execute();
                isOk = resp.isOk();
            }
        }
        return isOk;
    }
}
